package org.coderk.mybatis.controller.user;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.coderk.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author: TanJingyu
 * @create: 2021-06-28 16:35
 **/
@RestController
@RequestMapping("/user")
public class UserController{
    private final UserService service;
    private final SqlSessionFactory sqlSessionFactory;
    private final UserComponent userComponent;
    private final JdbcTemplate jdbcTemplate;
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public UserController(UserService service, SqlSessionFactory sqlSessionFactory, UserComponent userComponent, JdbcTemplate jdbcTemplate) {
        this.service = service;
        this.sqlSessionFactory = sqlSessionFactory;
        this.userComponent = userComponent;
        this.jdbcTemplate = jdbcTemplate;
    }

    public Object list() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.selectList("org.coderk.mybatis.mapper.UserMapper.selectAll");
    }

    @GetMapping("/async")
    public Object async() throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        userComponent.getName();
        return "async....";
    }

    @GetMapping("/update")
    public Object update() throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        service.update();
        return "update....";
    }

    @GetMapping("/update/countdownlatch")
    public Object updateCountDownLatch() throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                    jdbcTemplate.update("UPDATE user SET grade = grade + 1 WHERE id = 1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        return "update....";
    }

    @GetMapping("/countdownlatch")
    public Object countdownlatch() {
        countDownLatch.countDown();
        return "countdownlatch...";
    }

    @GetMapping("/insert")
    public Object insert() {
        System.out.println(Thread.currentThread().getName());
        service.insert();
        return "insert....";
    }
}
